<template>
  <view class="main-container" style="background-image: url('/static/images/img-banner.png');">
    <view class="nav-bar">
      <view class="nav-title">人工智能易学大模型</view>
    </view>

    <!-- 表单区域 -->
    <view class="form-container">
      <!-- AI 模型说明 -->
      <view class="ai-model-container">
        <view class="ai-model-header">
          <image class="ai-model-left-image" src="/static/images/img-AI.png" mode="aspectFit" lazy-load></image>
          <view class="ai-model-content">
            <text class="ai-model-title">{{ pageData.aiModelTitle }}</text>
            <view class="ai-model-desc-wrapper">
              <text class="ai-model-desc" :class="{ 'expanded': isDescExpanded }"
                @tap="isDescExpanded = !isDescExpanded">{{ pageData.aiModelDesc }}</text>
            </view>
          </view>
        </view>

        <view class="ai-model-tips">
          <view class="tip-badge">
            <image class="tip-icon" src="/static/images/icon-tip.png" mode="aspectFit" lazy-load></image>
            <view class="marquee-container">
              <text class="tip-text marquee">{{ pageData.aiModelTip }}</text>
            </view>
          </view>
        </view>

      </view>

      <view class="form-item-inline">
        <view class="form-label">{{ pageData.formLabels.surname }}</view>
        <view class="form-content">
          <u-input v-model="form.surname" placeholder="请输入姓氏" class="form-input"
            @input="validateChineseName('surname', form.surname)" />
        </view>
      </view>
      <view class="form-item-inline">
        <view class="form-label">{{ pageData.formLabels.name }}</view>
        <view class="form-content">
          <u-input v-model="form.name" placeholder="请输入名字" class="form-input"
            @input="validateChineseName('name', form.name)" />
        </view>
      </view>
      <view class="form-item-inline">
        <view class="form-label">{{ pageData.formLabels.gender }}</view>
        <view class="form-content">
          <view class="gender-select">
            <view v-for="item in ['男', '女']" :key="item.value" class="gender-option" @tap="form.gender = item">
              <view class="radio-button" :class="{ active: form.gender === item }">
              </view>
              <text>{{ item }}</text>
            </view>
          </view>
        </view>
      </view>
      <view class="form-item-inline">
        <view class="form-label">{{ pageData.formLabels.birth }}</view>
        <view class="form-content">
          <view class="birth-display" @tap="showDatePicker = true">
            <text v-if="form.birthText">{{ form.birthText }}</text>
            <text v-else class="placeholder">{{ pageData.birthPlaceholder }}</text>
            <u-icon name="arrow-right" color="#999"></u-icon>
          </view>
        </view>
      </view>

      <view class="user-count">已有 <span style="color:#dd302c">{{ userCount }}</span>人参与精准测算</view>
    </view>

    <view class="preview-container">
      <view class="banner-title" style="background-image: url('/static/images/bg-title1.png');">
        <text class="banner-title-text">预知你的一生感情状况</text>
      </view>

      <view class="preview-content">
        <image class="preview-image" src="/static/images/img-emotional.png" mode="widthFix" lazy-load></image>
      </view>
    </view>


    <!-- 替换第二个预览容器的内容 -->
    <view class="preview-container">
      <view class="banner-title" style="background-image: url('/static/images/bg-title2.png');">
        <text class="banner-title-text">易学大模型分析姻缘，扫除情感障碍</text>
      </view>
      <!-- 测算内容标题 -->
      <view class="section-title">
        <view class="section-title-bar"></view>
        <text class="section-title-text">{{ pageData.testCategoriesTitle }}</text>
      </view>

      <!-- 测算类别网格 -->
      <view class="category-grid">
        <view v-for="(item, index) in pageData.testCategories" :key="'category-' + index" class="category-item">
          <view class="category-icon"></view>
          <text class="category-title">{{ item.title }}</text>
        </view>
      </view>

      <!-- 桃花运分析 -->
      <view class="section-title">
        <view class="section-title-bar"></view>
        <text class="section-title-text">{{ pageData.peachBlossomTitle }}</text>
      </view>

      <view class="analysis-list">
        <view v-for="(item, index) in pageData.peachBlossomAnalysis" :key="'peach-' + index" class="analysis-item">
          <view class="bullet-point"></view>
          <text class="analysis-text">{{ item }}</text>
        </view>
      </view>

      <!-- 风险防范 -->
      <view class="section-title">
        <view class="section-title-bar"></view>
        <text class="section-title-text">{{ pageData.riskPreventionTitle }}</text>
      </view>

      <view class="analysis-list">
        <view v-for="(item, index) in pageData.riskPreventionItems" :key="'risk-' + index" class="analysis-item">
          <view class="bullet-point"></view>
          <text class="analysis-text">{{ item }}</text>
        </view>
      </view>
    </view>

    <view class="fixed-bottom-btn" @click="handleCalculate">开始测算</view>

    <date-picker :show="showDatePicker" @close="showDatePicker = false" @cancel="showDatePicker = false"
      @confirm="handleDatePickerConfirm" />

      <floating-report ref="report"  />
  </view>
</template>

<script>
import { getUserPayCount, putUserInfo } from '@/api/fortune';
import DatePicker from '@/components/date-picker';
import { trackButton, trackPageView } from '@/utils/track';
import { mapActions, mapGetters } from 'vuex';
import pageData from './data.js';

export default {
  name: 'MarriageHome',
  components: {
    DatePicker
  },
  computed: {
    ...mapGetters('fortune', ['userInfo']),
    ...mapGetters('system', ['userCount'])
  },
  data() {
    return {
      // 引入整个pageData对象
      pageData,
      isDescExpanded: false,
      // 日期选择控制
      showDatePicker: false,
      // 表单数据（本地临时存储，最终会同步到Vuex）
      form: {
        surname: '',
        name: '',
        gender: '男',
        year: 0,
        month: 0,
        day: 0,
        hour: 0,
        minute: 0,
        birthText: '',
      },
      pageViewTracker: null,
    }
  },
  mounted() {
    this.getPayCount();
    // 启动页面浏览埋点计时
    this.pageViewTracker = trackPageView({
      reportKey: '进入首页',
      reportVal: '首页浏览',
      pageName: '首页'
    });
    this.pageViewTracker.start();

    // 首页：初始化vuex数据
    this.initVuexData();
  },
  onHide() {
    // 页面离开时停止计时
    if (this.pageViewTracker) this.pageViewTracker.stop();
  },
  onUnload() {
    // 页面卸载时也停止计时
    if (this.pageViewTracker) this.pageViewTracker.stop();
  },
  methods: {
    ...mapActions('system', ['setUserId', 'setUserCount', 'setUserPhone']),
    ...mapActions('fortune', ['setUserInfo', 'setMarriageInfo', 'setOtherResultInfo']),
    ...mapActions('hehun', ['setHehunUserInfo', 'setHehunResultInfo', 'setOtherHehunUserInfo']),

    // 初始化vuex数据
    initVuexData() {
      // 重置payment模块的支付状态
      this.$store.dispatch('payment/resetPayStatus');
      
      // 重置fortune模块的结果数据
      this.setMarriageInfo([]);
      this.setOtherResultInfo([]);
      
      // 重置fortune模块的用户信息（清空用户输入）
      this.setUserInfo({
        surname: "",
        name: "",
        gender: "",
        year: 0,
        month: 0,
        day: 0,
        hour: 0,
        minute: 0,
        sourceForm: "test",
        userName: "",
        birthText: "",
      });
      
      // 重置hehun模块的数据
      this.setHehunUserInfo([]);
      this.setHehunResultInfo([]);
      this.setOtherHehunUserInfo([]);
      
      this.setUserId('100001');
      this.setUserPhone('');
    },

    // 获取支付人数
    async getPayCount() {
      try {
        const { data } = await getUserPayCount();
        this.setUserCount( Number(data.replace(/"/g, ''))  );
      } catch (error) {
        console.error('获取支付人数失败:', error);
      }
    },

    // 验证姓名只能输入汉字
    validateChineseName(field, value) {
      if (!value) return;
      const inputValue = field === 'surname' ? this.form.surname : this.form.name;
      const containsNonChinese = /[^\u4e00-\u9fa5]/.test(inputValue);
      if (containsNonChinese) {
        const filteredValue = inputValue.replace(/[^\u4e00-\u9fa5]/g, '');
        this.$nextTick(() => {
          if (field === 'surname') {
            this.form.surname = filteredValue;
          } else {
            this.form.name = filteredValue;
          }
        });
      }
    },
    // 处理日期选择器确认 - 使用ES6解构赋值
    handleDatePickerConfirm({ year, month, day, hour, minute, birthText }) {
      // 直接使用解构赋值更新表单数据
      Object.assign(this.form, { year, month, day, hour, minute, birthText });
    },

    // 开始测算
    async handleCalculate() {
      // 检查用户输入是否完整有效
      if (!this.form.surname) {
        this.$show.showToast('请输入您的姓氏');
        return;
      }
      // 名字不是必填项，如果没有填写名字，根据性别设置默认值
      if (!this.form.name) {
        this.form.name = this.form.gender === '男' ? '先生' : '女士';
      }
      if (!this.form.gender) {
        this.$show.showToast('请选择您的性别');
        return;
      }
      if (!this.form.birthText) {
        this.$show.showToast('请选择您的生辰');
        return;
      }
      // 埋点：点击开始测算
      trackButton({
        reportKey: '开始测算按钮',
        reportVal: '填写表单',
        pageName: '首页'
      });
      // 构建用户信息对象
      const userInfo = {
        surname: this.form.surname,
        name: this.form.name,
        userName: this.form.surname + this.form.name,
        gender: this.form.gender,
        year: this.form.year,
        month: this.form.month,
        day: this.form.day,
        hour: this.form.hour,
        minute: this.form.minute,
        birthText: this.form.birthText
      };
      this.setUserInfo(userInfo)
      try {
        const { data } = await putUserInfo(userInfo);
        this.setUserId(data)
        uni.navigateTo({
          url: '/pages/interlude/index',
        });
      } catch (error) {
        this.$show.showToast(error.message || '操作失败，请重试');
      }
    },
  }
}
</script>
<style lang="scss" scoped>
@import "./page.scss";
</style>